// TabSheet.cpp : implementation file
//

#include "stdafx.h"
#include "SheetPageTabCtrl.h"
#include "Page2.h"
#include "Page3.h"
// CTabSheet

IMPLEMENT_DYNAMIC(CTabSheet, CTabCtrl)

CTabSheet::CTabSheet()
{
	m_PageNum = 0;
	m_nCurrentPage = 0;
}

CTabSheet::~CTabSheet()
{
}


BEGIN_MESSAGE_MAP(CTabSheet, CTabCtrl)
	ON_NOTIFY_REFLECT(TCN_SELCHANGE, &CTabSheet::OnTcnSelchange)
END_MESSAGE_MAP()



// CTabSheet message handlers



BOOL CTabSheet::AddPage(CString szTitle, CDialog * pDialog, UINT ID, bool ShowFirst)
{
	if (MAX_PAGES == m_PageNum){
		return FALSE;
	}
	m_PageNum++;

	EnableThemeDialogTexture(pDialog->GetSafeHwnd(), ETDT_ENABLETAB);

	pages page;
	page.m_pages = pDialog;
	page.m_IDD = ID;
	page.m_title = szTitle;

	m_TabPages.push_back(page);

	int m_sel = GetCurSel();

	m_TabPages.at(m_PageNum - 1).m_pages->Create(m_TabPages.at(m_PageNum - 1).m_IDD, this);



	InsertItem(m_PageNum - 1, m_TabPages.at(m_PageNum - 1).m_title);

	SetRect(m_PageNum - 1);

	if (!ShowFirst)
		SetCurFocus(m_PageNum - 1);
	else
		if (m_sel != -1)
			SetCurSel(m_sel);
	RedrawWindow();

	return TRUE;
}

BOOL CTabSheet::DeletePage(CString szTitle)
{
	for (UINT i = 0; i < m_TabPages.size(); i++)
	{
		if (m_TabPages.at(i).m_title = szTitle)
		{
			if (DeleteItem(i))
			{

				m_PageNum--;
				delete(m_TabPages.at(i).m_pages);
				m_TabPages.erase(m_TabPages.begin() + i);
				RedrawWindow();
				return true;
			}
			else
				return false;
		}
	}
	return false;
}

BOOL CTabSheet::DeletePage(UINT site)
{
	if (m_TabPages.size() != 0 || site < m_TabPages.size())
	{
		m_PageNum--;
		delete(m_TabPages.at(site).m_pages);
		m_TabPages.erase(m_TabPages.begin() + site);
		RedrawWindow();
		return TRUE;
	}
	return false;
}


void CTabSheet::SetRect(UINT nIdx)
{
	CRect tabRect, itemRect;
	int nX = 0, nY = 0, nXc = 0, nYc = 0;
	UINT nCount = 0;

	GetClientRect(&tabRect);
	GetItemRect(0, &itemRect);
	nX = itemRect.left;
	nY = itemRect.bottom + 1;
	nXc = tabRect.right - itemRect.left - 2;
	nYc = tabRect.bottom - nY - 2;

	//	for (nCount = 0; nCount < m_PageNum; nCount++)
	//	{
	if (GetCurSel() == (m_PageNum - 1))
	{
		m_TabPages.at(m_TabPages.size() - 1).m_pages->SetWindowPos(&wndTop, nX, nY, nXc, nYc, SWP_SHOWWINDOW);
	}
	else
	{
		m_TabPages.at(m_TabPages.size() - 1).m_pages->SetWindowPos(&wndTop, nX, nY, nXc, nYc, SWP_HIDEWINDOW);
	}
	//	}
}

void CTabSheet::OnTcnSelchange(NMHDR *pNMHDR, LRESULT *pResult)
{
	if (m_nCurrentPage != GetCurFocus()){
		m_TabPages.at(m_nCurrentPage).m_pages->ShowWindow(SW_HIDE);
		m_nCurrentPage = GetCurFocus();
		if (m_nCurrentPage == 1) {
			((CPage2*)m_TabPages.at(m_nCurrentPage).m_pages)->ReLoad();
		}
		else if (m_nCurrentPage == 2) {
			((CPage3*)m_TabPages.at(m_nCurrentPage).m_pages)->ReLoad();
		}
		m_TabPages.at(m_nCurrentPage).m_pages->ShowWindow(SW_SHOW);
	}

	*pResult = 0;
}
